const Service = require('egg').Service
const schedule = require('node-schedule')

class CourseTerminfoService extends Service {
  async index(categoryId) {
    console.log(categoryId)
    const { ctx, app } = this
    // // 获取对应分类课程
    const courseRes = await ctx.find('Course', { where: { categoryId }}, 'findAll')
    const tmp = []
    if (courseRes.length > 0) {
      courseRes.forEach(item => {
        tmp.push(item.dataValues)
      })
    }
    // // 添加任务队列
    const taskId = await ctx.service.cache.task.addTask()
    // 获取当前类别
    const curCategory = await ctx.find('CourseCategory', { where: { categoryId }, attributes: ['categoryName'] })
    // 获取当前课程类别期数
    const terminfoTmp = []
    const terminfoRes = await ctx.find('CourseTerminfo', { where: { categoryId }}, 'findAll')
    if (terminfoRes.length > 0) {
      terminfoRes.forEach(item => {
        terminfoTmp.push(item.dataValues)
      })
    }
    let num = 0
    const cId = categoryId
    const job = schedule.scheduleJob('*/5 * * * * *', async() => {
      if (tmp.length <= 0) {
        console.log('数据爬取完毕')
        await ctx.service.cache.task.updateTaskData({
          taskId,
          num,
          finished: true,
          title: curCategory.dataValues.categoryName
        })
        await ctx.service.cache.index.addLog(cId, num, 2)
        job.cancel()
        return
      }
      let { schoolSN, courseId, termId, categoryId } = tmp.pop()
      const courseInfo = {}
      const temp = {}
      let index = 0
      const postData = []
      do {
        const terminfoUrl = `${app.config.moocDomain}/course/${schoolSN}-${courseId}?tid=${termId}`
        const res = await ctx.curl(terminfoUrl, {
          method: 'get'
        })
        const terminfoString = res.data.toString()
        const termDtoPat = /termDto\s=\s(\{[\s\S]*?\}\;)/
        if (!courseInfo.list) {
          const terminfoPat = /termInfoList\s=\s(\[[\s\S]*?\]\;)/
          /* eslint-disable */
          eval('courseInfo.list=' + terminfoString.match(terminfoPat)[1])
        }
        /* eslint-disable */
        eval('courseInfo.detailInfo=' + terminfoString.match(termDtoPat)[1])
        postData.push(courseInfo.detailInfo)
        temp[termId] = true
        if (courseInfo.list[++index]) {
          termId = courseInfo.list[index].id
        }
      } while(!temp[termId] || courseInfo.list[index])

      const terminfoCount = await this.createTerminfo(postData, courseId, categoryId, terminfoTmp)
      num += terminfoCount
      await ctx.service.cache.task.updateTaskData({
        taskId,
        num,
        finished: false,
        title: curCategory.dataValues.categoryName
      })
    })
    return { taskId, num }
  }

  async createTerminfo(data, courseId, categoryId, terminfos) {
    const { ctx } = this
    const postData = []
    const tmp = []
    for (let i = 0, len = data.length; i < len; i++) {
      const { id, enrollCount, outLineDto, startTime, endTime } = data[i]

      const dict = {
        termId: id,
        courseId,
        categoryId,
        enrollCount,
        outLine: outLineDto.outLine,
        startTime: new Date(+startTime),
        endTime: new Date(+endTime)
      }
      const index = terminfos.findIndex(terminfo => terminfo.termId === id)
      if (index !== -1) {
        if (terminfos[index].enrollCount !== enrollCount) {
          dict.id = terminfos[index].id
          postData.push(dict)
        }
      } else {
        if (!tmp.includes(id)) {
          postData.push(dict)
          tmp.push(id)
        }
      }
    }
    if (postData.length > 0) {
      const res = await ctx.bulkCreate('CourseTerminfo', postData, { updateOnDuplicate: ['enrollCount'] })
      return res.length
    }
    return 0
  }
}

module.exports = CourseTerminfoService
